package com.ruoyi.info.controller;

import com.google.code.kaptcha.Producer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 前端验证码操作处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/info")
public class FrontCodeController {

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @GetMapping("/code")
    public AjaxResult getFrontCode(HttpServletResponse response) throws IOException {
        //准备返回的结果
        AjaxResult ajax = AjaxResult.success();


        // 验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.FRONT_CODE_KEY + uuid;


        // 生成4位数字验证码
        Random rnd = new Random();
        StringBuilder sbCode = new StringBuilder(4);
        for(int i=0; i < 4; i++){
            sbCode.append(rnd.nextInt(10)+"");
        }

        String codeText = sbCode.toString();

        System.out.println("本次验证码是：" + codeText);

        //验证码存入redis
        redisCache.setCacheObject(verifyKey, codeText, Constants.CODE_EXPIRATION, TimeUnit.MINUTES);

        ajax.put("uuid", uuid);
        ajax.put("code", codeText);
        return ajax;
    }
}
